<!-- 角色管理 -->
<template>
    <div class="common-layout">
        <el-backtop :bottom="50" target=".main" ref="backTop" :visibility-height="10"></el-backtop>
        <el-container>
            <el-header>
                <el-space>
                    <el-select class="frame" placeholder="请选择用户状态" v-model="seacherData.status">
                        <el-option v-for="item in statusData" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                    <el-select class="frame" placeholder="请选择用户会员等级" v-model="seacherData.level">
                        <el-option v-for="item in vipGrade" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                    <el-select class="frame" placeholder="请选择用户性别" v-model="seacherData.gender">
                        <el-option v-for="item in genderData" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                    <el-form ref="ruleFormRef" :model="seacherData" status-icon 
                        style="position: relative;top: 10px;">
                        <el-space>
                            <el-form-item prop="id" :rules="[{ pattern: /^[0-9]*$/, message: '请输入数字' ,trigger: 'blur'}]">
                                <el-input class="fix_input" v-model.trim="seacherData.id" placeholder="请输入用户ID" clearable
                                    @clear="init()" />
                            </el-form-item>
                            <el-form-item>
                                <el-input class="fix_input" v-model.trim="seacherData.nickname" placeholder="请输入昵称"
                                    clearable @clear="init()" />
                            </el-form-item>
                            <el-form-item>
                                <el-button :icon="Search" type="primary"
                                    @click="searchAdminName(ruleFormRef)">查找</el-button>
                            </el-form-item>
                        </el-space>
                    </el-form>
                </el-space>
            </el-header>
            <el-main>
                <div class="el-scrollbar__wrap metaBox">
                    <el-backtop :bottom="100" ref="backTop" :visibility-height="5" target=".metaBox .el-scrollbar__wrap" />
                    <!-- 表格组件 -->
                    <el-table :data="tableData" border style="width: 100%;height: 100%;" class="scrollbar-demo-item"
                        v-loading="listLoading" element-londing-text="正在加载中...">
                        <el-table-column prop="id" label="用户ID" align="center" />
                        <el-table-column prop="nickname" label="昵称" align="center" />
                        <el-table-column prop="phone" label="手机号码" align="center" />
                        <el-table-column prop="gender" label="性别" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.gender == 2 ? '' : scope.row.gender == 1 ? 'danger' : 'warning'">{{
                                    scope.row.gender == 2 ? '男' : scope.row.gender == 1 ? '女' : '保密'
                                }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="level" label="会员等级" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.level == 0 ? 'info' : 'warning'">{{ scope.row.level == 0 ? "普通会员" :
                                    'vip会员' }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="birthday" label="生日" align="center">
                            <!-- 时间转换 -->
                            <template #default="scope">
                                {{ scope.row.birthday ? handleTime(scope.row.birthday,'年月日') : "—" }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.status == 0 ? 'danger' : ''">{{ scope.row.status == 0 ? "冻结" : "激活"
                                }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="gmtLastLogin" label="上次登录时间" align="center">
                            <!-- 时间转换 -->
                            <template #default="scope">
                                {{ traversalTime(scope.row.gmtLastLogin) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="lastLoginIp" label="上次登录IP" align="center">
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="200px">
                            <template #default="scope">
                                <el-button type="primary" @click="handleFreeze(scope.$index, scope.row)">{{ scope.row.status
                                    == 0 ? "激活" : "冻结"
                                }}</el-button>
                                <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>

                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-main>
            <el-footer>
                <Paging v-bind="pagination" @page-change="pageChange" />
            </el-footer>
        </el-container>
    </div>

    <!-- 对话框组件 -->
    <el-dialog v-model="dialogVisible" title="编辑" width="60%" destroy-on-close>
        <!-- 修改功能表单组件 -->
        <el-form ref="ruleFormRef" :model="form" status-icon :rules="rules" class="demo-ruleForm" label-width="200px">
            <el-form-item prop="nickname" label="用户昵称：">
                <el-input class="fix_input" v-model.trim="form.nickname" type="text" autocomplete="off"
                    placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item prop="phone" label="用户手机号：">
                <el-input class="fix_input" v-model.trim="form.phone" type="text" autocomplete="off" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="用户性别" prop="gender" class="is-required">
                <el-select class="frame" placeholder="请选择用户性别" v-model="form.gender">
                    <el-option v-for="item in genderData.slice(0,3)" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="用户等级" prop="level" class="is-required">
                <el-select class="frame" placeholder="请选择用户等级" v-model="form.level">
                    <el-option v-for="item in vipGrade.slice(0,2)" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="用户状态" prop="status">
                <el-select class="frame" placeholder="请选择用户状态" v-model="form.status">
                    <el-option v-for="item in statusData.slice(0,2)" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="sure(ruleFormRef);">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { Search } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { post } from '@/utils/http';
import { nextTick, onMounted, reactive, ref } from 'vue';
import Paging from '@/components/paging/Paging.vue'
import { ClassPagination } from '#/index';
import { ElMessage } from "element-plus"
import { traversalTime, handleTime } from '@/utils/ProcessingTime'
// 数据初始化
onMounted(() => {
    init()
})

// 控制对话框组件的显示隐藏
const dialogVisible = ref(false)

const backTop = ref()                                   //回到顶部
const pagination = reactive(new ClassPagination())      //分页
let tableData: TypeVipAdmin[] = reactive([])               //表格数据
let listLoading = ref(false)            //加载效果
// 表单绑定的数据
let form = reactive({
    nickname: '',//用户昵称
    phone: '',//用户手机
    gender: 1,//用户性别
    level: 1,//用户等级
    status: 1,//用户状态
    id: 0
})

/**
 * 表单验证
 */
const rules = {
    nickname: [
        { required: true, message: "请输入昵称", trigger: 'blur' },
    ],
    phone: [
        { required: true, trigger: 'blur', message: "请输入您的手机号码！" },
        { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: "请正确填写您的手机号码" }
    ],
    gender: [
        { required: true, message: "请选择用户性别类型！", trigger: 'blur' }
    ],
    level: [
        { required: true, message: "请选择用户会员类型！", trigger: 'blur' }
    ],
    status: [
        { required: true, message: "请选择用户状态", trigger: 'blur' }
    ]
}

/**
 * 状态
 */
const statusData = reactive([
    { value: 0, name: "冻结" },
    { value: 1, name: "激活" },
    { value: "", name: "全部" },
]);
/**
 * 会员
 */
const vipGrade = reactive([
    { value: 0, name: "普通会员" },
    { value: 1, name: "vip会员" },
    { value: "", name: "全部" },
]);
/**
 * 性别
 */
const genderData = reactive([
    { value: 2, name: "男" },
    { value: 1, name: "女" },
    { value: -1, name: "保密" },
    { value: "", name: "全部" },
]);

// 搜索所需的数据
let seacherData = reactive({
    id: "",
    nickname: "",
    level: undefined,
    gender: undefined,
    status: undefined,
})
// 搜索操作
function searchAdminName(formEl: FormInstance | undefined) {
    formEl?.validate((valid) => {
        if (valid) {
            init()
        } else {
            return false
        }

    })
}

/**
 * 获取初始化数据，用于渲染页面
 */
function init() {
    listLoading.value = true
    // 请求管理员列表需要传递的参数
    let adminListData = reactive({
        _gp: "admin.user",
        _mt: "list",
        id: seacherData.id,//用户ID
        nickname: seacherData.nickname,//用户昵称
        level: seacherData.level, //用户等级
        birthday: '',//生日
        gender: seacherData.gender,//用户性别
        status: seacherData.status,//用户状态
        pageNo: pagination.page,//当前页码
        limit: pagination.limit//每页页码长度
    })
    // 请求管理员列表接口拿到管理员列表信息
    post(adminListData).then(res => {
        console.log("====管理员数据======");
        console.log(res);
        let { data: { total, items },errno } = res
        if (200 === errno) {
            // console.log("====管理员数据======");
            // console.log(data.data.items);
            pagination.total = total
            tableData.length = 0;
            tableData.push(...items)
            listLoading.value = false
            nextTick(() => {
                backTop.value.$el.click?.()
            })
        } else {
            ElMessage.error("用户ID必须是数字")
        }
    }).catch(err => {
        console.log(err);

    })


}

const ruleFormRef = ref<FormInstance>()
//子传父的自定义事件
function pageChange(e: TypePage) {
    pagination.page = e.page
    pagination.limit = e.limit
    init()
}

/**
 * 获取修改前的数据
 * @param index 当前下标
 * @param row 当前下标的数据
 */
const handleEdit = (index: number, row: TypeVipAdmin) => {
    console.log(row)
    dialogVisible.value = true;
    form.nickname = row.nickname ? row.nickname : "";
    form.phone = row.phone;
    form.gender = row.gender;
    form.level = row.level;
    form.status = row.status;
    form.id = row.id;
    // Object.assign(form, row)
    console.log(form);

}

/**
 * 冻结解冻操作
 * @param index 当前下标
 * @param row 当前下标的数据
 */
const handleFreeze = (index: number, row: TypeVipAdmin) => {
    let data = {
        _gp: 'admin.user',
        _mt: 'editStatus',
        userId: row.id,
        status: row.status == 0 ? 1 : 0,
    }
    post(data).then(res => {
        let { errno } = res
        if (200 === errno) {
            ElMessage.success(row.status == 1 ? '冻结成功' : '激活成功')
            init()
        }
    }).catch(err => {
        console.log(err);
    })
}

/**
 * 修改功能
 * @param formEl 表单验证结果
 */
function sure(formEl: FormInstance | undefined) {

    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            console.log("=====要提交的表单数据=====");
            console.log(form);

            let data = {
                _gp: 'admin.user',
                _mt: 'edit',
                user: JSON.stringify(form)
            }
            post(data).then(res => {
                let { errno } = res
                if (200 === errno) {
                    dialogVisible.value = false
                    ElMessage.success('修改成功')
                    init()
                }
                resetForm(formEl)
            }).catch(err => {
                console.log(err);
            })
        } else {
            return false
        }
    })
}

/**
 * 表单重置
 * @param formEl 表单验证结果
 */
function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.resetFields()
}

</script>
  

<style scoped lang="less">
.scrollbar-demo-item {
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
}

.metaBox {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60vh;
    text-align: center;
}

.fix_input {
    width: 200px;
}

.treechile {
    position: relative;
    right: 0px;
    color: red;
}
</style>